package com.sz.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diboot.iam.entity.IamUser;
import com.diboot.iam.mapper.IamUserMapper;
import com.sz.mes.entity.warehouse.Area;
import com.sz.mes.mapper.WarehouseMapper;
import com.sz.mes.service.warehouse.AreaService;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.validator.constraints.Length;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.diboot.core.vo.*;
import com.diboot.iam.annotation.OperationCons;
import com.diboot.iam.annotation.BindPermission;
import com.diboot.iam.annotation.Log;
import com.sz.mes.entity.Warehouse;
import com.sz.mes.dto.WarehouseDTO;
import com.sz.mes.vo.WarehouseListVO;
import com.sz.mes.vo.WarehouseDetailVO;
import com.sz.mes.service.WarehouseService;
import com.sz.mes.controller.BaseCustomCrudRestController;
import lombok.extern.slf4j.Slf4j;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * 仓库 相关Controller
 *
 * @author hem
 * @version 1.0
 * @date 2023-05-25
 * Copyright © szhs
 */
@RestController
@RequestMapping("/warehouse")
@BindPermission(name = "仓库")
@Slf4j
public class WarehouseController extends BaseCustomCrudRestController<Warehouse> {

    @Autowired
    private WarehouseService warehouseService;

    @Autowired
    private IamUserMapper iamUserMapper;

    @Autowired
    private WarehouseMapper warehouseMapper;

    @Autowired
    private AreaService areaService;

    /**
     * 查询ViewObject的分页数据
     * <p>
     * url请求参数示例: /list?field=abc&pageIndex=1&orderBy=abc:DESC
     * </p>
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_LIST)
    // @BindPermission(name = OperationCons.LABEL_LIST, code = OperationCons.CODE_READ)
    @GetMapping("/list")
    public JsonResult getViewObjectListMapping(WarehouseDTO queryDto, Pagination pagination) throws Exception {
        QueryWrapper<Warehouse> warehouseQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(queryDto.getWarehouseName())) {
            warehouseQueryWrapper.like("warehouse_name", queryDto.getWarehouseName());
        } else {
            return super.getViewObjectList(queryDto, pagination, WarehouseListVO.class);
        }
        return super.getEntityListWithPaging(warehouseQueryWrapper, pagination);
    }

    /**
     * 根据资源id查询ViewObject
     *
     * @param id ID
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/{id}")
    public JsonResult getViewObjectMapping(@PathVariable("id") Long id) throws Exception {
        return super.getViewObject(id, WarehouseDetailVO.class);
    }

    /**
     * 创建资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_CREATE)
    // @BindPermission(name = OperationCons.LABEL_CREATE, code = OperationCons.CODE_WRITE)
    @PostMapping("/")
    public JsonResult createEntityMapping(@Valid @RequestBody Warehouse entity) throws Exception {
        try {
            String warehouseName = entity.getWarehouseName();
            QueryWrapper<Warehouse> warehouseQueryWrapper = new QueryWrapper<>();
            warehouseQueryWrapper.eq("warehouse_name", warehouseName);
            Warehouse warehouse = warehouseMapper.selectOne(warehouseQueryWrapper);
            if (warehouse != null) {
                return JsonResult.FAIL_EXCEPTION("该货区名称已经存在");
            }

            List<String> managerNameList = new ArrayList<>();
            String managerId = entity.getManagerId();
            String[] managerIdArray = managerId.split(",");
            for (String id : managerIdArray) {
                IamUser iamUser = iamUserMapper.selectById(id);
                String realname = iamUser.getRealname();
                managerNameList.add(realname);
            }
            String delimter = ",";
            String managerName = String.join(delimter, managerNameList);
            entity.setManagerName(managerName);
            super.createEntity(entity);

            //创建仓库的同时，默认创建一个货区
//            Area area = new Area();
//            area.setAreaName("00");
//            area.setAreaNumber("00");
//            area.setWarehouseId(entity.getId());
//            areaService.createEntity(area);
        } catch (Exception e) {
            return JsonResult.FAIL_OPERATION("编码重复");
        }
        return JsonResult.OK("创建成功");
    }

    /**
     * 根据ID更新资源对象
     *
     * @param entity
     * @return JsonResult
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_UPDATE)
    // @BindPermission(name = OperationCons.LABEL_UPDATE, code = OperationCons.CODE_WRITE)
    @PutMapping("/{id}")
    public JsonResult updateEntityMapping(@PathVariable("id") Long id, @Valid @RequestBody Warehouse entity) throws Exception {
        try {
            List<String> managerNameList = new ArrayList<>();
            String managerId = entity.getManagerId();
            String[] managerIdArray = managerId.split(",");
            //如果从一个负责人更新到多个负责人，则遍历一下，反之，直接更新
            if (managerIdArray.length > 1) {
                for (String manager : managerIdArray) {
                    IamUser iamUser = iamUserMapper.selectById(manager);
                    String realname = iamUser.getRealname();
                    managerNameList.add(realname);
                }
                String delimter = ",";
                String managerName = String.join(delimter, managerNameList);
                entity.setManagerName(managerName);
                return super.updateEntity(id, entity);
            } else {
                return super.updateEntity(id, entity);
            }
        }catch (Exception e){
            e.printStackTrace();
            return JsonResult.FAIL_EXCEPTION("该货区名称已经存在");
        }
    }

    /**
     * 根据id删除资源对象
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DELETE)
    // @BindPermission(name = OperationCons.LABEL_DELETE, code = OperationCons.CODE_WRITE)
    @DeleteMapping("/{id}")
    public JsonResult deleteEntityMapping(@PathVariable("id") Long id) throws Exception {
        return super.deleteEntity(id);
    }

    /**
     * 查询树形仓库结构
     *
     * @return
     * @throws Exception
     */
    @Log(operation = OperationCons.LABEL_DETAIL)
    // @BindPermission(name = OperationCons.LABEL_DETAIL, code = OperationCons.CODE_READ)
    @GetMapping("/getTreeWarehouse")
    public JsonResult getTreeWarehouse() throws Exception {
        return warehouseService.getTreeWarehouse();
    }
}
